package com.term.dao.utils;

import com.term.domain.BaseDomain;
import com.term.dao.error.DefaultError;
import com.term.dao.exception.BaseSystemException;

import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 对查询语句的处理工具类
 * Created by chenGang on 2017/1/6.
 */
public class QueryUtil {

    /**
     * 去掉sql/jpql的select子句，未考虑union的情况（union等复杂查询请自己拼接sql），用于pageQuery
     *
     * @param sql
     * @return
     */
    public static String removeSelect(String sql) {
        int beginPos = sql.toLowerCase().indexOf("from");
        return sql.substring(beginPos);
    }

    /**
     * 去掉sql的orderby子句，用于pageQuery
     *
     * @param sql
     * @return
     */
    public static String removeOrders(String sql) {
        Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(sql);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, "");
        }
        m.appendTail(sb);
        return sb.toString();
    }

    public static <T extends BaseDomain> String getTableName(Class<T> clazz){
        String tableName;
        Table tableAnnotation = clazz.getAnnotation(Table.class);
        if (tableAnnotation != null)
            tableName = tableAnnotation.name();
        else{
            Entity entityAnnotation = clazz.getAnnotation(Entity.class);
            if (entityAnnotation != null)
                tableName = entityAnnotation.name();
            else
                throw new BaseSystemException(DefaultError.TABLE_OR_ENTITY_ANNOTATION_NOT_FOUND);
        }
        return tableName.toLowerCase();
    }
}
